﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Text.RegularExpressions;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;

namespace Digitalmes.Hubs
{
    [AuthorizeJwt]
    public class ChatHub : Hub
    {
        // 存储连接ID与用户的映射关系
        private static readonly ConcurrentDictionary<string, UserConnection> _connections =
            new ConcurrentDictionary<string, UserConnection>();

        private readonly ILogger<ChatHub> _logger;

        public ChatHub(ILogger<ChatHub> logger)
        {
            _logger = logger;
        }

        // 客户端连接时调用
        public override async Task OnConnectedAsync()
        {
            // 从Context中获取用户信息（需要与认证系统集成）
            var userId = Context.User?.Claims?.FirstOrDefault().Value ?? "Anonymous";
            var connectionId = Context.ConnectionId;

            var userConnection = new UserConnection
            {
                UserId = userId,
                ConnectionId = connectionId,
                ConnectedAt = DateTime.Now
            };

            _connections[connectionId] = userConnection;

            _logger.LogInformation($"用户 {userId} 已连接，连接ID: {connectionId}");

            // 通知所有用户有新用户上线
            await Clients.All.SendAsync("UserConnected", userId, userConnection.UserName);

            await base.OnConnectedAsync();
        }

        // 客户端断开连接时调用
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            var connectionId = Context.ConnectionId;

            if (_connections.TryRemove(connectionId, out UserConnection userConnection))
            {
                _logger.LogInformation($"用户 {userConnection.UserId} 已断开连接");

                // 通知所有用户有用户下线
                await Clients.All.SendAsync("UserDisconnected", userConnection.UserId, userConnection.UserName);
            }

            await base.OnDisconnectedAsync(exception);
        }

        // 加入群组
        public async Task JoinGroup(string groupName)
        {
            var connectionId = Context.ConnectionId;

            if (_connections.TryGetValue(connectionId, out UserConnection userConnection))
            {
                await Groups.AddToGroupAsync(connectionId, groupName);

                _logger.LogInformation($"用户 {userConnection.UserId} 加入了群组 {groupName}");

                // 通知群组内的其他用户
                await Clients.Group(groupName).SendAsync("ReceiveMessage", "系统",
                    $"{userConnection.UserName} 加入了群组", DateTime.Now.ToString("HH:mm"));
            }
        }

        // 离开群组
        public async Task LeaveGroup(string groupName)
        {
            var connectionId = Context.ConnectionId;

            if (_connections.TryGetValue(connectionId, out UserConnection userConnection))
            {
                await Groups.RemoveFromGroupAsync(connectionId, groupName);

                _logger.LogInformation($"用户 {userConnection.UserId} 离开了群组 {groupName}");

                // 通知群组内的其他用户
                await Clients.Group(groupName).SendAsync("ReceiveMessage", "系统",
                    $"{userConnection.UserName} 离开了群组", DateTime.Now.ToString("HH:mm"));
            }
        }

        // 发送消息到群组
        public async Task SendMessageToGroup(string groupName, string message)
        {
            var connectionId = Context.ConnectionId;

            if (_connections.TryGetValue(connectionId, out UserConnection userConnection))
            {
                _logger.LogInformation($"用户 {userConnection.UserId} 向群组 {groupName} 发送消息: {message}");

                // 向指定群组的所有客户端发送消息
                await Clients.Group(groupName).SendAsync("ReceiveMessage",
                    userConnection.UserName, message, DateTime.Now.ToString("HH:mm"));
            }
        }

        // 发送私聊消息
        public async Task SendPrivateMessage(string targetUserId, string message)
        {
            var connectionId = Context.ConnectionId;

            if (_connections.TryGetValue(connectionId, out UserConnection senderConnection))
            {
                // 查找目标用户的连接ID（实际项目中可能需要更复杂的映射关系）
                foreach (var connection in _connections.Values)
                {
                    if (connection.UserId == targetUserId)
                    {
                        _logger.LogInformation($"用户 {senderConnection.UserId} 向用户 {targetUserId} 发送私聊消息: {message}");

                        // 向发送者确认消息已发送
                        await Clients.Caller.SendAsync("ReceivePrivateMessage",
                            senderConnection.UserName, message, DateTime.Now.ToString("HH:mm"), true);

                        // 向接收者发送消息
                        await Clients.Client(connection.ConnectionId).SendAsync("ReceivePrivateMessage",
                            senderConnection.UserName, message, DateTime.Now.ToString("HH:mm"), false);

                        break;
                    }
                }
            }
        }

        // 获取在线用户列表
        public async Task<List<UserConnection>> GetOnlineUsers()
        {
            return _connections.Values.ToList();
        }
    }

    public class UserConnection
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public string ConnectionId { get; set; }
        public DateTime ConnectedAt { get; set; }
    }
}
